﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

namespace Lyh.Common.Parser
{
    public static class JsonParser
    {

        public static string ToJson(this object value)
        {
            var json = ToJson(value, false, false);
            return json;
        }

        public static string ToJson(this object value, bool format, bool camelCase)
        {
            var formatting = format ? Formatting.Indented : Formatting.None;
            var settings = new JsonSerializerSettings
            {
                ContractResolver = camelCase ? new CamelCasePropertyNamesContractResolver() : new DefaultContractResolver()
            };
            var json = JsonConvert.SerializeObject(value, formatting, settings);
            return json;
        }

        public static T ToObject<T>(this string json)
        {
            var t = ToObject<T>(json, false);
            return t;
        }

        public static T ToObject<T>(this string json, bool camelCase)
        {
            var settings = new JsonSerializerSettings
            {
                ContractResolver = camelCase ? new CamelCasePropertyNamesContractResolver() : new DefaultContractResolver()
            };
            var t = JsonConvert.DeserializeObject<T>(json, settings);
            return t;
        }
    }
}
